/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Accelerometer;

/**
 *
 * @author gianmariospacagna
 */
public class CircularArray {

    int size;
    float[] array;
    int head;
    int n;

    public CircularArray(int size) {
        this.size = size;
        array = new float[size];
        head = 0;
        n = 0;

    }

    public void addElement(float elem) {
        if (head == size - 1) {
            array[0] = elem;
            head = 0;
        } else {
            array[head] = elem;
        }
        head++;
        n++;
    }

    public float getAverage() {
        float avg = 0;

        for (float s : array) {
            avg += s;
        }
        if (n < size) {
            return avg / n;
        }
        return avg / size;


    }

    public float getFirstHalfAverage() {
        float avg = 0;
        int k = 0;
        int i = head;


        while (k <= size / 2) {
            avg += array[i % 50];
            i++;
            k++;
        }

        if (n<50)
            return 0;
        return avg / (size / 2);


    }

    public float getSecondHalfAverage() {
        float avg = 0;
        int k = 0;
        int i = head+25;


        while (k <= size / 2) {
            avg += array[i % 50];
            i++;
            k++;
        }

        if (n<50)
            return 0;
        return avg / (size / 2);
    }

    public float getVariance() {
        if (n >= size) {
            float avg = getAverage();
            float var = 0;
            for (int i = size / 2; i < size; i++) {
                var += ((array[i] - avg) * (array[i] - avg));



            }

            return var /= size - 1;
        } else {
            return 0;
        }
    }

    public boolean isFull() {
        if (n >= size) {
            return true;
        } else {
            return false;
        }
    }

    public float getSlope() {
        float[] avgDiff = new float[size];
        for (int i = 1; i < size; i++) {
            float avgl = 0;
            float avgr = 0;
            for (int il = 0; il < i; il++) {
                avgl += array[il];
            }
            avgl /= i;
            for (int ir = i; ir < size; ir++) {
                avgr += array[ir];
            }
            avgr /= (size - i);
            avgDiff[i] = Math.abs(avgr - avgl);

        }
        float max = avgDiff[0];
        int pos = 1;
        for (int i = 1; i < size; i++) {
            if (avgDiff[i] > max) {
                max = avgDiff[i];
                pos = i;
            }
        }
        return (array[pos] - array[pos - 1]);
    }

    public int getN() {
        return n;
    }
}
